package com.rslai.base.tool.servertest.model;

import com.rslai.base.tool.autotest.mock.model.Expectation;
import com.rslai.base.tool.autotest.mock.model.HttpExpectation;
import com.rslai.base.tool.autotest.mock.model.RpcExpectation;
import com.rslai.base.tool.servertest.objectfactory.BeanUtils;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public class MockInfo {
    public static final String SOURCE = "source";
    public static final String TARGET = "target";
    public static final String KEY = "key";
    public static final String RETURN_VALUE = "returnValue";
    public static final String SERVICE = "service";
    private List<KeyValueStore> params;

    public MockInfo(List<KeyValueStore> params) {
        this.params = params;
    }

    public Expectation createExpectation() {
        String body = getBody();
        if (isRpc()) {
            RpcExpectation expectation = new RpcExpectation();
            expectation.setBody(body);
            return expectation;
        }
        if (StringUtils.isNotBlank(body)) {
            HttpExpectation expectation = new HttpExpectation();
            expectation.setBody(body);
            return expectation;
        }
        Object expectation = get("return");
        Object[] parameters = BeanUtils.getParameters(Arrays.asList(new KeyValueStore[]{new KeyValueStore("return", expectation)}), new Class[]{HttpExpectation.class});
        return (Expectation) parameters[0];
    }

    private String getBody() {
        if (StringUtils.isNotBlank(getReturnValue())) {
            return getReturnValue();
        }
        if ((this.params == null) || (this.params.size() < 1)) {
            return null;
        }
        Object returnValue = get("return");
        if ((returnValue instanceof String)) {
            return returnValue.toString();
        }
        return null;
    }

    private boolean isRpc() {
        return getService().toLowerCase().startsWith("rpc:");
    }

    public String getService() {
        return (String) get("service");
    }

    public String getKey() {
        return (String) get("key");
    }

    public String getTarget() {
        return (String) get("target");
    }

    public String getSource() {
        return (String) get("source");
    }

    private <T> T get(String key) {
        for (KeyValueStore param : this.params) {
            if (param.getName().equalsIgnoreCase(key)) {
                return (T) param.getValue();
            }
        }
        return null;
    }

    public String getReturnValue() {
        return (String) get("returnValue");
    }
}

